package com.mid;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created by Lxk on 2019/5/17.
 */

/**
 * 可以尝试用非递归
 */
public class Solution144 {

    void preOrderVisit(TreeNode cur, List<Integer> res) {
        if (cur == null) {
            return;
        }
        res.add(cur.val);
        preOrderVisit(cur.left, res);
        preOrderVisit(cur.right, res);
    }

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        preOrderVisit(root, res);
        return res;
    }

    /**
     * 二叉树前序遍历非递归方式
     *
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            res.add(node.val);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return res;
    }
}
